package com.msxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.constant.JwtClaimsConstant;
import com.msxt.dto.UsersEntity;
import com.msxt.properties.JwtProperties;
import com.msxt.result.R;
import com.msxt.service.TokenService;
import com.msxt.service.UsersService;
import com.msxt.utils.JwtUtil;
import com.msxt.utils.MPUtil;
import com.msxt.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("users")
public class UsersController {

	@Autowired
	private UsersService userService;

//	@Autowired
//	private TokenService tokenService;
	@Autowired
	private JwtProperties jwtProperties;
	/**
	 * 登录
	 */
	@IgnoreAuth
	@PostMapping("/login")
	public R login(String username, String password, HttpServletRequest request) {
		UsersEntity user = userService.getOne(new QueryWrapper<UsersEntity>().eq("username", username));
		if(user == null || !user.getPassword().equals(password)) {
			return R.error("账号或密码不正确");
		}

		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.ADMNI_ID, user.getId());
		claims.put(JwtClaimsConstant.USERNAME, username);
		claims.put(JwtClaimsConstant.ROLE, user.getRole());
		claims.put(JwtClaimsConstant.TABLE_NAME, "users");

		String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(),
				jwtProperties.getAdminTtl(),
				claims);
		return R.ok().put("token", token);
	}



	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping("/register")
	public R register(@RequestBody UsersEntity user) {
		if(userService.getOne(new QueryWrapper<UsersEntity>().eq("username", user.getUsername())) != null) {
			return R.error("用户已存在");
		}
		userService.save(user);
		return R.ok();
	}

	/**
	 * 退出
	 */
	@GetMapping("/logout")
	public R logout(HttpServletRequest request) {
		// JWT是无状态的，退出由前端删除token即可
		return R.ok("退出成功");
	}

	/**
	 * 密码重置
	 */
	@IgnoreAuth
	@PostMapping("/resetPass")
	public R resetPass(String username, HttpServletRequest request) {
		UsersEntity user = userService.getOne(new QueryWrapper<UsersEntity>().eq("username", username));
		if(user == null) {
			return R.error("账号不存在");
		}
		user.setPassword("123456");
		userService.updateById(user);
		return R.ok("密码已重置为：123456");
	}

	/**
	 * 分页列表
	 */
	@GetMapping("/page")
	public R page(@RequestParam Map<String, Object> params, UsersEntity user) {
		QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
		PageUtils page = userService.queryPage(params,
				MPUtil.sort(MPUtil.between(MPUtil.allLike(wrapper, user), params), params));
		return R.ok().put("data", page);
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	public R list(UsersEntity user) {
		QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(user, "user"));
		return R.ok().put("data", userService.list(wrapper));
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") String id) {
		UsersEntity user = userService.getById(id);
		return R.ok().put("data", user);
	}

	@GetMapping("/session")
	public R getCurrUser(HttpServletRequest request) {
		// 从请求属性中获取用户ID
		Object userIdObj = request.getAttribute("userId");
		if (userIdObj == null) {
			log.warn("未找到用户ID属性");
			return R.error(401, "用户未登录");
		}

		Long id;
		try {
			id = Long.parseLong(userIdObj.toString());
		} catch (NumberFormatException e) {
			log.error("用户ID格式错误: {}", userIdObj);
			return R.error(401, "无效的用户ID");
		}

		log.info("获取用户ID: {}", id);

		UsersEntity user = userService.getById(id);
		if (user == null) {
			return R.error(401, "用户不存在");
		}

		return R.ok().put("data", user);
	}

	/**
	 * 保存用户
	 */
	@PostMapping("/save")
	public R save(@RequestBody UsersEntity user) {
		if(userService.getOne(new QueryWrapper<UsersEntity>().eq("username", user.getUsername())) != null) {
			return R.error("用户已存在");
		}
		userService.save(user);
		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@PostMapping("/update")
	public R update(@RequestBody UsersEntity user) {
		UsersEntity u = userService.getOne(new QueryWrapper<UsersEntity>().eq("username", user.getUsername()));
		if(u != null && !u.getId().equals(user.getId()) && u.getUsername().equals(user.getUsername())) {
			return R.error("用户名已存在");
		}
		userService.updateById(user);
		return R.ok();
	}

	/**
	 * 删除用户
	 */
	@DeleteMapping("/delete")
	public R delete(@RequestBody Long[] ids) {
		userService.removeByIds(Arrays.asList(ids));
		return R.ok();
	}
}